<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存并继续',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并关闭',
      icon: '',
      type: 'primary',
      hidden: !isEdit || !!data.form.associationBillNo,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createPersonName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12 full flex-c">
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="单据单号" prop="takeStockBillNo">
              <ElInputBox :data="form" dataName="takeStockBillNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据状态" prop="takeStockState">
              <ElSelectBox :data="form" dataName="takeStockState" :options="options.state" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="单据备注" prop="takeStockRemark" class="wAuto">
              <ElInputBox :data="form" dataName="takeStockRemark" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop isAuto>
          <template #btn>
            <el-link type="primary" icon="Filter" @click="pup.state = true">选择范围</el-link>
            <el-divider direction="vertical" />
            <el-link type="primary" @click="exportBtn" icon="Download">导出明细</el-link>
          </template>
          <el-auto-resizer class="full">
            <template #default="{ height }">
              <TableBoxMxVirtualized :height="height" :data="{
                filter: (el: any) => {
                  const search = data.search
                  return (el.takeStockResult === search.typeCode || search.typeCode === -1) && el.goodsName.includes(search.goodsName)
                },
                disabled: !isEdit,
                tbody: form.detailList,
                search: data.search,
                thead: data.thead
              }">
                <template #headL>
                  <ElInputBox :data="data.search" dataName="goodsName" :width="300" placeholder="物料名称" />
                </template>
                <template #headR>
                  <el-radio-group v-model="data.search.typeCode">
                    <el-radio-button :label="`${item.label}(${getNumber(item.value)})`" :value="item.value"
                      v-for="item in data.type" />
                  </el-radio-group>
                </template>
              </TableBoxMxVirtualized>
            </template>
          </el-auto-resizer>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
  <ElPupFormBox :pup="pup">
    <template #default="{ form }">
      <ElFormItemBox label="物料类型" prop="groupCodes">
        <ElSelectBox :data="form" dataName="groupCodes" multiple :options="options.goodGroup" />
      </ElFormItemBox>
      <ElFormItemBox label="物料分类" prop="categoryCodes">
        <ElSelectBox :data="form" dataName="categoryCodes" multiple :options="options.goodType" />
      </ElFormItemBox>
      <ElFormItemBox label="供应商" prop="supplierCodes">
        <ElSelectBox :data="form" dataName="supplierCodes" multiple :options="options.supplier" />
      </ElFormItemBox>
      <ElFormItemBox label="数量" prop="count">
        <ElNumberBox :data="form" dataName="count" />
      </ElFormItemBox>
      <ElFormItemBox label="是否随机" prop="isRandom">
        <ElSwitchBox :data="form" dataName="isRandom" />
      </ElFormItemBox>
    </template>
  </ElPupFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs'; // 引入逻辑
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { dataInfo, options } = useListComponent();
const router = useRouter();
const { proxy } = getCurrentInstance() as any;
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    takeStockID: '', // 出库主键ID
    takeStockBillNo: '', // 出库主键ID
    takeStockState: 1, // 盘点单据状态：1盘点中（待确认）；2盘点完成（已确认）
    takeStockRemark: '', // 出库主键ID
    detailList: []
  },
  search: {
    typeCode: -1,
    goodsName: '',
  },
  thead: [
    {
      label: '规格编码',
      prop: 'specificationCode',
      align: 'center', // 默认居中对齐
      width: 100
    },
    {
      label: '物料名称',
      prop: 'goodsName',
      align: 'left', // 默认居中对齐
      width: 200
    },
    {
      label: '规格型号',
      prop: 'specificationName',
      align: 'left', // 根据提供的信息指定左对齐
      width: 120
    },
    {
      label: '供应商',
      prop: 'supplierName',
      align: 'left', // 默认居中对齐
      width: 120
    },
    {
      label: '物料类型',
      prop: 'categoryName',
      align: 'center', // 默认居中对齐
      width: 80
    },
    {
      label: '生产批次',
      prop: 'productionBatchNumber',
      align: 'center', // 默认居中对齐
      width: 100
    },
    {
      label: '生产日期',
      prop: 'productionDate',
      align: 'center', // 默认居中对齐
      width: 120
    },
    {
      label: '库位',
      prop: 'warehouseArea',
      align: 'center', // 默认居中对齐
      width: 80
    },
    {
      label: '库位',
      prop: 'areaShelf',
      align: 'center', // 默认居中对齐
      width: 80
    },
    {
      label: '库存数量',
      prop: 'originalStockQuantity',
      align: 'center', // 默认居中对齐
      width: 120
    },
    {
      label: '盘点数量',
      prop: 'takeStockQuantity',
      align: 'center', // 默认居中对齐
      width: 120,
      formType: 'number',
      changeBtn: (value: any, row: any) => {
        if (value) {
          const takeStockNum = proxy.$count(`${row.takeStockQuantity || 0}-${row.originalStockQuantity || 0}`)
          if (takeStockNum > 0) {
            //盘盈
            row.takeStockResult = 2
          } else if (takeStockNum < 0) {
            //盘亏
            row.takeStockResult = 3
          } else {
            //持平
            row.takeStockResult = 1
          }
          row.gainorLossQuantity = takeStockNum
        } else {
          row.takeStockResult = 0
          row.gainorLossQuantity = null
        }
        row.isTakeStockName = takeStockType[row.takeStockResult] || '待盘'
      }
    },
    {
      label: '物料单位',
      prop: 'goodsUnitName',
      align: 'center', // 默认居中对齐
      width: 80
    },
    {
      label: '盘点结果',
      prop: 'isTakeStockName',
      align: 'center', // 默认居中对齐
      width: 80,
      formType: 'tag',
      formKey: 'takeStockResult',
      options: [
        {
          label: '待盘',
          value: 0,
          type: 'info'
        },
        {
          label: '持平',
          value: 1,
          type: ''
        },
        {
          label: '盘盈',
          value: 2,
          type: 'success'
        },
        {
          label: '盘亏',
          value: 3,
          type: 'danger'
        },
      ]
    },
    {
      label: '盈亏数量',
      prop: 'gainorLossQuantity',
      align: 'center', // 默认居中对齐
      width: 80,
      value: (row: any) => {
        return row.gainorLossQuantity || row.gainorLossQuantity === 0 ? row.gainorLossQuantity : '--'
      }
    },
    {
      label: '备注',
      prop: 'deliveryMxRemark',
      align: 'center', // 默认居中对齐
      width: null, // 没有指定宽度
      formType: 'text',
    }
  ],
  type: [
    {
      label: '全部',
      value: -1
    },
    {
      label: '待盘点',
      value: 0
    },
    {
      label: '持平',
      value: 1
    },
    {
      label: '盘盈',
      value: 2
    },
    {
      label: '盘亏',
      value: 3
    }
  ]
});
const isEdit = ref(true)

const pup = reactive({
  state: false,
  typeName: 0,
  title: `选择盘点范围`,
  width: 600,
  height: 'auto',
  form: {
    warehouseCode: '', // 仓库代码，空值查询全部
    groupCodes: [], // 物料分组代码，空值查询全部
    categoryCodes: [], // 物料分类代码，空值查询全部
    supplierCodes: [], // 供应商代码，空值查询全部
    warehouseAreaCodes: [], // 库区编码，空值查询全部
    areaShelfCodeCodes: [], // 库位编码，空值查询全部
    count: null, // 盘点数量
    isRandom: false // 是否随机
  },
  btns: [
    {
      title: '确认',
      type: 'primary',
      click: (pup: any) => {
        pup.loading = true
        proxy.$api.Warehouse.QueryMatchPanDianStockGoodsList({
          ...pup.form,
          warehouseCode: data.form.warehouseCode,
          onlyStocked: 0,//-1：显示全部、0：不显示0库存、1：仅显示0库存
        })
          .then((res: any) => {
            data.form.detailList = res.filter((el: any) => el.originalStockQuantity > 0).map((el: any) => ({
              ...el,
              takeStockResult: 0,
              productionDate: proxy.$day(el.productionDate)
            }))
            pup.state = false
          }).catch(() => {
            pup.loading = false
          })
      }
    }
  ]
});
//添加关联单明细
const getNumber = (type: any) => {
  let count = data.form.detailList.reduce((accumulator: number, current: any) => {
    return current.takeStockResult === type || type === -1 ? accumulator + 1 : accumulator;
  }, 0);
  return count
}
const addMx = (rows: any) => {

  const _rows = Array.isArray(rows) ? rows : [rows]
  let _arr = _rows.map((el: any) => ({
    outStockQuantity: el.requestQuantity, // 待出库数量
    outStockRemark: el.remark, // 申请数量
  }))
  data.form.detailList.push(
    ..._arr
  )
}
const takeStockType: any = {
  0: '待盘',
  1: '持平',
  2: '盘盈',
  3: '盘亏',
}
//获取数据
const getForm = async () => {
  const _query: any = route.query
  setLoading()
  //是否新建
  if (!!!_query.code) {
    data.loading = false
    if (!!!data.form.warehouseCode) {
      proxy.$api.Warehouse.GetMatchWarehouses()
        .then((res: any) => {
          data.form.warehouseCode = res[0].warehouseCode;
          pup.state = true
        })
        .catch(() => { });
    }
    return
  }
  proxy.$api.TakeStock.GetTakeStockBillDetail({
    takeStockBillNo: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type)
      data.form = {
        ...res,
        detailList: res.detailList.map((el: any) => ({
          ...el,
          productionDate: proxy.$day(el.productionDate),
          takeStockResultName: takeStockType[el.takeStockResult] || '待盘'
        }))
      }
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const saveBtn = (form: any, isConfirm: boolean = false) => {
  setLoading('正在保存数据，请稍等')
  const _form: any = {
    takeStockID: form.takeStockID, // 
    warehouseCode: form.warehouseCode, // 
    takeStockRemark: form.takeStockRemark, // 备注
    detailList: form.detailList.map((el: any) => (
      {
        stockGoodsCode: el.stockGoodsCode, // 库存物品编码
        takeStockQuantity: el.takeStockQuantity, // 盘点库存数量（实盘数量），空值时表示未盘点
        takeStockResult: el.takeStockResult, // 盈亏结果：0未盘点；1持平（无盈亏）；2盘盈；3盘亏
        gainorLossQuantity: el.gainorLossQuantity, // 盘点盈亏数量（正数标签盘盈，负数标签盘亏）
        takeStockRemark: el.takeStockRemark, // 盘点备注说明
      }
    ))
  }
  // return
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.TakeStock.CreateTakeStockBill(_form)
        .then((res: any) => {
          if (isConfirm) {
            _sun()
          } else {
            router.push({
              query: {
                type: 2, //页面类型
                code: res, //仓库code
              }
            });
            setTimeout(() => {
              getForm();
            }, 100);
            sendMsg('save', true);
          }
        })
        .catch(() => {
          data.loading = false
        });
      break;
    case '2'://编辑
      proxy.$api.TakeStock.UpdateTakeStockBill(_form)
        .then((res: any) => {
          data.loading = false
          if (isConfirm) {
            _sun()
          }
        })
        .catch(() => {
          data.loading = false
        });
      break;
    default:
      break;
  }
  function _sun() {
    closeBtn('保存成功')
  }
};
const closeBtn = (message?: string) => {
  if (message) {
    proxy.$message(message)
  }
  data.loading = false
  sendMsg('save', true);
  // getForm()
  window.close();
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
// 导出数据
const exportBtn = () => {
  setLoading()
  proxy.$exportData(
    {
      thead: data.thead,
      tbody: data.form.detailList,
      fileName: '盘点明细',
    },
    data,
  );
};
import { getSupplier, goodGroup, getGoodType } from '@/utils/optionsArr.ts';
import { forEach } from 'mathjs';
onMounted(() => {
  getForm();
  getSupplier(options, 'supplier')//获取供应商
  goodGroup(options, 'goodGroup')//获取类型
  getGoodType(options, 'goodType')//获取类型
});
</script>
